//
//  LayoutTextView.m
//  LayoutTextView
//
//  Created by JiaHaiyang on 16/7/6.
//  Copyright © 2016年 PlutusCat. All rights reserved.
//
#import "LayoutTextView.h"

#define textViewFont [UIFont systemFontOfSize:18]

static CGFloat maxHeight = 80.0f;
static CGFloat leftFloat = 5.0f;
static CGFloat textViewHFloat = 33.0f;
static CGFloat sendBtnW = 50.0f;
static CGFloat sendBtnH = 33.0f;

@interface LayoutTextView()<UITextViewDelegate>
@property (assign, nonatomic) CGFloat superHight;
@property (assign, nonatomic) CGFloat textViewY;
@property (assign, nonatomic) CGFloat sendButtonOffset;
@property (assign, nonatomic) CGFloat keyBoardHight;
@property (assign, nonatomic) CGRect originalFrame;

@property (assign ,nonatomic) BOOL isHiddenTextField;

@end

@implementation LayoutTextView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        
        _originalFrame = frame;
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hideTextView) name:@"hiddenTextView" object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showTextView) name:@"showTextView" object:nil];
        
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWasShow:)
                                                     name:UIKeyboardWillShowNotification object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWillBeHidden:)
                                                     name:UIKeyboardWillHideNotification object:nil];
        self.backgroundColor = HEXCOLOR(kColorGray6, 1);
        
        UITextView *textView = [[UITextView alloc] init];
        textView.delegate    = self;
        textView.textColor   = HEXCOLOR(kColorGray4, 1);
        textView.backgroundColor = [UIColor whiteColor];
        textView.font = textViewFont;
        textView.layer.cornerRadius  = 5;
        textView.layer.masksToBounds = YES;
        textView.layer.borderWidth   = 0.5;
        textView.layer.borderColor   = [[UIColor lightGrayColor] CGColor];
        textView.layoutManager.allowsNonContiguousLayout = YES;
        [self addSubview:textView];
        self.textView = textView;
        
        UIButton *sendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [sendBtn setTitleColor:HEXCOLOR(kColorGray2, 1) forState:UIControlStateNormal];
        [sendBtn setTitle:@"发送" forState:UIControlStateNormal];
        [sendBtn setBackgroundColor:[UIColor whiteColor]];
        sendBtn.layer.cornerRadius  = 5;
        sendBtn.layer.masksToBounds = YES;
        sendBtn.layer.borderWidth   = 0.5;
        sendBtn.layer.borderColor   = [[UIColor lightGrayColor] CGColor];
        [sendBtn addTarget:self action:@selector(sednBtnAction) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:sendBtn];
        self.sendBtn =  sendBtn;

        CGFloat textViewX = leftFloat;
        CGFloat textViewW = Main_Screen_Width-(3*textViewX+sendBtnW);
        CGFloat textViewH = textViewHFloat;
        CGFloat textViewY = (self.frame.size.height-textViewH)*0.5;
        _textView.frame = CGRectMake(textViewX, textViewY, textViewW, textViewH);
        _textView.backgroundColor = [UIColor whiteColor];

        _textViewY = textViewY;
        _sendButtonOffset = (self.frame.size.height-sendBtnH)*0.5;
        _superHight = self.frame.size.height;
        
        
        _placeHolderLabel = [[UILabel alloc] init];
        _placeHolderLabel.frame = CGRectMake(textViewX+5, textViewY, textViewW-5, textViewH);
        _placeHolderLabel.font = [UIFont systemFontOfSize:14];
        _placeHolderLabel.textColor = [UIColor colorWithRed:201 / 255.0 green:201 / 255.0 blue:201 / 255.0 alpha:1];
        [self addSubview:_placeHolderLabel];
        
    }
    return self;
}

- (void)sednBtnAction{
    
    if (_sendBlock) {
        _sendBlock(_textView);
    }
    [_textView resignFirstResponder];
    _textView.text = _placeholder;
    _textView.textColor = HEXCOLOR(kColorGray4, 1);
}

- (void)begingEdit{
    [_textView becomeFirstResponder];
}

- (void)setPlaceholder:(NSString *)placeholder{
    _placeholder = placeholder;
    _placeHolderLabel.text = _placeholder;
}

- (void)layoutSubviews{
    [super layoutSubviews];
    
    CGFloat sendBtnX = CGRectGetMaxX(_textView.frame)+leftFloat;
    CGFloat sendBtnY = (self.frame.size.height-sendBtnH)*0.5;
    _sendBtn.frame = CGRectMake(sendBtnX, sendBtnY, sendBtnW, sendBtnH);
    
    CGFloat textViewX = leftFloat;
    CGFloat textViewW = Main_Screen_Width-(3*textViewX+sendBtnW);
    CGFloat textViewH = textViewHFloat;
    CGFloat textViewY = (self.frame.size.height-textViewH)*0.5;
    _textView.frame = CGRectMake(textViewX, textViewY, textViewW, textViewH);
    
    _placeHolderLabel.frame = CGRectMake(textViewX+5, textViewY, textViewW-5, textViewH);
}

#pragma mark - == UITextViewDelegate ==
- (void)textViewDidBeginEditing:(UITextView *)textView{
    _textView.text = @"";
    _textView.textColor = [UIColor blackColor];

}
- (void)textViewDidChange:(UITextView *)textView{
    
    CGRect frame = textView.frame;
    CGSize constraintSize = CGSizeMake(frame.size.width, MAXFLOAT);
    CGSize size = [textView sizeThatFits:constraintSize];
    if (size.height<=frame.size.height) {

    }else{
        if (size.height>=textViewHFloat){
            size.height = textViewHFloat;
            textView.scrollEnabled = YES;   // 允许滚动
        }else{
            textView.scrollEnabled = NO;    // 不允许滚动
        }
    }
    textView.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, size.height);
    
    CGFloat superHeight = CGRectGetMaxY(textView.frame)+_textViewY;
    
    [UIView animateWithDuration:0.15 animations:^{
        [self setFrame:CGRectMake(self.frame.origin.x, Main_Screen_Height-(_keyBoardHight+superHeight), self.frame.size.width, superHeight)];
    }];
    
    if([textView.text length] == 0){
        self.placeHolderLabel.text = self.placeholder;
    }else{
        self.placeHolderLabel.text = @"";//这里给空
    }
}

- (void)textViewDidChangeSelection:(UITextView *)textView{

    CGRect r = [textView caretRectForPosition:textView.selectedTextRange.end];
    CGFloat caretY =  MAX(r.origin.y - textView.frame.size.height + r.size.height + 8, 0);
    if (textView.contentOffset.y < caretY && r.origin.y != INFINITY) {
        textView.contentOffset = CGPointMake(0, caretY);
    }
}

- (void)textViewDidEndEditing:(UITextView *)textView{
    textView.scrollEnabled = NO;
    CGRect frame = textView.frame;
    textView.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, textViewHFloat);
    [textView layoutIfNeeded];
    
    [_textView resignFirstResponder];
    
}

#pragma mark - == 键盘弹出事件 ==

//隐藏输入框
-(void)hideTextView{
    _isHiddenTextField = YES;
    self.hidden = YES;
}

//展示输入框
-(void)showTextView{
    _isHiddenTextField = NO;
    self.hidden = NO;
}

- (void)keyboardWasShow:(NSNotification*)notification{
    
    //******************解决多次通知的问题***********************
    
    CGRect begin = [[[notification userInfo] objectForKey:@"UIKeyboardFrameBeginUserInfoKey"] CGRectValue];
    
    CGRect end = [[[notification userInfo] objectForKey:@"UIKeyboardFrameEndUserInfoKey"] CGRectValue];
    
    //因为第三方键盘或者是在键盘加个toolbar会导致回调三次，这个判断用来判断是否是第三次回调，原生只有一次
    
    if(begin.size.height>0 && ((begin.origin.y-end.origin.y)== begin.size.height)){
        
        //处理逻辑
        _originalFrame = self.frame;

    }
    //************************************************************
    
    if (_isHiddenTextField == YES) {
        self.hidden = YES;
    }else{
        self.hidden = NO;
        CGRect keyBoardFrame = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
        
        _keyBoardHight = keyBoardFrame.size.height;
        
        [self translationWhenKeyboardDidShow:_keyBoardHight];

    }
    
}

- (void)keyboardWillBeHidden:(NSNotification*)notification{
    
    [self translationWhenKeyBoardDidHidden];
}

- (void)translationWhenKeyboardDidShow:(CGFloat)keyBoardHight{
    [UIView animateWithDuration:0.25 animations:^{
        
        self.frame = CGRectMake(self.frame.origin.x, Main_Screen_Height-(keyBoardHight+self.frame.size.height), self.frame.size.width, self.frame.size.height);
    }];
    
}

- (void)translationWhenKeyBoardDidHidden{
    [UIView animateWithDuration:0.25 animations:^{
        self.frame = _originalFrame;
    }];
}


@end
